﻿using System;
using System.IO;
using System.Linq;
using System.Xml.Linq;

namespace SharePointUtilitiesForDevelopers.Tests.Mapper
{
    /// <summary>
    /// Helper class for service reponse testing.
    /// </summary>
    internal static class ServiceResponseTestHelper
    {
        /// <summary>
        /// Loads the XML file.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <returns></returns>
        internal static XElement LoadXml(string path)
        {
            try
            {
                using (var reader = new StreamReader(path))
                {
                    var contents = reader.ReadToEnd();
                    return XElement.Parse(contents);
                }
            }
            catch(Exception ex)
            {
                throw new InvalidOperationException("Failed to open test file: " + path, ex);   
            }
        }

        /// <summary>
        /// Gets the first element.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        internal static XElement GetFirstElement(string path, string name)
        {
            var element = LoadXml(path);
            return GetFirstElement(element, name);
        }

        /// <summary>
        /// Gets the first element.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        internal static XElement GetFirstElement(XElement element, string name)
        {
            return element.DescendantsAndSelf().First(ele => ele.Name.LocalName == name); 
        }
    }
}